package com.baskode.bookare.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import com.baskode.bookare.model.Book;

public class DoubanBookFetcher implements IBookFetcher {

	public DoubanBookFetcher(){
		
	}
	
	private static final String API_KEY = "0d86cf7a546c8b3c28946e6efd45a1b4";
	private static final String PRIVATE_KEY = "d6afdd51042abcd1";
	
	public Book getBookByIsbn(String isbn) throws MalformedURLException {
		// TODO Auto-generated method stub
		Book book = new Book();
		
		URL url = new URL(getIsbnUrl(isbn));
		BufferedReader br;
		String s = "";
		StringBuffer sb = new StringBuffer("");
		try {
			br = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8"));

			while ((s = br.readLine()) != null) {
				sb.append(s +"\r\n");				
			}
			br.close();

		String result = new String(sb.toString());
		
		System.out.println(result);
		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return book;
	}
	
	private String getIsbnUrl(String isbn){
		StringBuffer sb = new StringBuffer();
		sb.append("http://api.douban.com/book/subject/isbn/")
			.append(isbn)
			.append("?")
			.append("apikey=")
			.append(API_KEY);
		
		return sb.toString();
	}

}
